<template>
  <div class="project-form">
    <el-form ref="writeRequireRef" class="form-container" label-width="0px">
      <div class="form-row">
        <div class="form-item full-width">
          <span class="label-wrap">调研的行业及重点 </span>
          <div class="tag-container">
            <div class="tags-wrap">
              <el-tag v-for="(tag, idx) in surveyIndustryKeynoteTags" :key="idx" closable
                @close="removeTag('surveyIndustryKeynoteTags', idx)" size="small" class="tag-item">
                {{ tag }}
              </el-tag>
            </div>
            <div class="input-add-group">
              <el-input v-model="newSurveyIndustryKeynoteTag" placeholder="自定义标签" class="custom-input" size="small"
                :border="false" maxlength="20" />
              <el-button type="primary" size="small"
                @click="addTag('surveyIndustryKeynoteTags', 'newSurveyIndustryKeynoteTag')" class="add-btn">
                添加
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="form-row">
        <div class="form-item full-width">
          <span class="label-wrap">评研要求</span>
          <div class="tag-container">
            <div class="tags-wrap">
              <el-tag v-for="(tag, idx) in surveyRequireTags" :key="idx" closable
                @close="removeTag('surveyRequireTags', idx)" size="small" class="tag-item">
                {{ tag }}
              </el-tag>
            </div>
            <div class="input-add-group">
              <el-input v-model="newSurveyRequireTag" placeholder="自定义标签" class="custom-input" size="small"
                :border="false" maxlength="20" />
              <el-button type="primary" size="small" @click="addTag('surveyRequireTags', 'newSurveyRequireTag')"
                class="add-btn">
                添加
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="form-row">
        <div class="form-item full-width">
          <span class="label-wrap">使用知识库</span>
          <div class="tag-container">
            <div class="tags-wrap">
              <el-tag v-for="(item, idx) in knowledgeBaseTags" :key="idx" closable @close="removeKnowledgeTag(idx)"
                size="small" class="tag-item" :class="item.fileUrl ? 'file-tag' : ''">
                {{ item.fileName }}
                <i v-if="item.fileUrl" class="el-icon-document el-icon--right" title="已上传文件"></i>
              </el-tag>
            </div>
            <div class="input-upload-group">
              <div class="input-add-group knowledge-input-group">
                <el-input v-model="newKnowledgeBaseTag" placeholder="自定义标签" class="custom-input" size="small"
                  :border="false" maxlength="30" />
                <el-button type="primary" size="small" @click="addKnowledgeTextTag()" class="add-btn">
                  添加
                </el-button>
              </div>
              <el-upload class="knowledge-upload" :action="uploadUrl" :headers="headers"
                :on-success="handleFileUploadSuccess" :on-remove="handleFileRemove" :before-remove="confirmFileRemove"
                :limit="5" :on-exceed="handleFileExceed" size="small" :auto-upload="true">
                <el-button type="primary" size="small" class="upload-btn">
                  上传文件
                </el-button>
              </el-upload>
            </div>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'
import { addRequire } from '@/api/whitepaper/myproject'
import { getToken } from "@/utils/auth";

export default {
  name: "WriteRequire",
  props: {
    formData: { type: Object, default: () => ({}) },
    projectId: { type: Number, default: 0 }
  },
  data() {
    return {
      surveyIndustryKeynoteTags: [],
      surveyRequireTags: [],
      knowledgeBaseTags: [],
      newSurveyIndustryKeynoteTag: "",
      newSurveyRequireTag: "",
      newKnowledgeBaseTag: "",
      baseApi: process.env.VUE_APP_BASE_API,
      uploadUrl: `${process.env.VUE_APP_BASE_API}/system/oss/file/upload`,
      headers: { Authorization: "Bearer " + getToken() },
      fileList: []
    };
  },
  watch: {
    formData: {
      deep: true,
      immediate: true,
      handler(val = {}) {
        const requireData = val.whitePaperRequire || {};
       if (requireData.surveyIndustryKeynoteTags?.length) {
        this.surveyIndustryKeynoteTags = [...requireData.surveyIndustryKeynoteTags];
      }
      if (requireData.surveyRequireTags?.length) {
        this.surveyRequireTags = [...requireData.surveyRequireTags];
      }
      if (requireData.knowledgeBaseTags?.length) {
        this.knowledgeBaseTags = this.formatKnowledgeTags(requireData.knowledgeBaseTags || []);
      }
      this.fileList = this.formatFileList(this.knowledgeBaseTags);
    }
    },
    projectId: {
      immediate: true,
      handler(newVal) {
        if (newVal) this.getRequireInfo(newVal);
      }
    },
    "$store.getters.token": {
      handler() {
        this.headers.Authorization = "Bearer " + getToken();
      }
    }
  },
  methods: {
    formatKnowledgeTags(tags) {
      if (!Array.isArray(tags)) return [];
      return tags.map(item => typeof item === 'string'
        ? { fileName: item, fileUrl: '', delFlag: '0' }
        : { ...item, delFlag: item.delFlag || '0' });
    },
    formatFileList(knowledgeTags) {
      return knowledgeTags
        .filter(item => item.fileUrl)
        .map(item => ({
          name: item.fileName,
          url: this.getFullFileUrl(item.fileUrl),
          raw: { name: item.fileName }
        }));
    },
    getFullFileUrl(fileUrl) {
      if (!fileUrl) return '';
      return fileUrl.startsWith('http') || fileUrl.startsWith(this.baseApi)
        ? fileUrl
        : `${this.baseApi}${fileUrl}`;
    },
    getRelativeFileUrl(fullUrl) {
      if (!fullUrl) return '';
      return fullUrl.startsWith(this.baseApi)
        ? fullUrl.replace(this.baseApi, '')
        : fullUrl;
    },
    addTag(tagArrKey, inputKey) {
      const val = this[inputKey].trim();
      if (val && val.length <= 20 && !this[tagArrKey].includes(val)) {
        this[tagArrKey].push(val);
        this[inputKey] = "";
        this.syncToParent();
      }
    },
    removeTag(tagArrKey, idx) {
      this[tagArrKey].splice(idx, 1);
      this.syncToParent();
    },
    addKnowledgeTextTag() {
      const val = this.newKnowledgeBaseTag.trim();
      if (val && val.length <= 30 && !this.knowledgeBaseTags.some(item => item.fileName === val && !item.fileUrl)) {
        this.knowledgeBaseTags.push({ fileName: val, fileUrl: '', delFlag: '0' });
        this.newKnowledgeBaseTag = "";
        this.syncToParent();
      }
    },
    removeKnowledgeTag(idx) {
      this.knowledgeBaseTags.splice(idx, 1);
      this.fileList = this.formatFileList(this.knowledgeBaseTags);
      this.syncToParent();
    },
    handleFileUploadSuccess(response, file) {
      if (response.code === 200 && response.data?.fileUrl) {
        this.knowledgeBaseTags.push({
          fileName: file.name.length > 30 ? file.name.slice(0, 30) + '...' : file.name,
          fileUrl: this.getRelativeFileUrl(response.data.fileUrl),
          delFlag: '0'
        });
        this.fileList = this.formatFileList(this.knowledgeBaseTags);
        this.syncToParent();
      } else {
        this.$message.error("文件上传失败：" + (response.msg || '接口响应异常'));
      }
    },
    handleFileRemove(file, fileList) {
      const fileName = file.name;
      this.knowledgeBaseTags = this.knowledgeBaseTags.filter(
        item => !(item.fileName === fileName && item.fileUrl)
      );
      this.syncToParent();
    },
    confirmFileRemove(file) {
      return this.$confirm(`确定删除文件「${file.name}」？`);
    },
    handleFileExceed(files, fileList) {
      this.$message.warning(`最多只能上传5个文件，本次选择了${files.length}个`);
    },
    syncToParent() {
      this.$emit("updateForm", {
        whitePaperRequire: {
          surveyIndustryKeynoteTags: [...this.surveyIndustryKeynoteTags],
          surveyRequireTags: [...this.surveyRequireTags],
          knowledgeBaseTags: [...this.knowledgeBaseTags]
        }
      });
    },
    async validate(callback) {
      if (this.surveyIndustryKeynoteTags.length === 0) {
        callback(false);
        return;
      }
      if (this.surveyRequireTags.length === 0) {
        callback(false);
        return;
      }
      const submitData = {
        projectId: this.projectId,
        surveyIndustryKeynote: this.surveyIndustryKeynoteTags.join(','),
        surveyRequire: this.surveyRequireTags.join(','),
        knowledgeBaseList: this.knowledgeBaseTags.map(tag => ({
          projectId: this.projectId,
          originFileName: tag.fileName,
          fileUrl: tag.fileUrl,
          delFlag: tag.delFlag
        })),
        delFlag: "0"
      };
      try {
        await addRequire(submitData, { headers: this.headers });
        callback(true);
      } catch (err) {
        let errorMsg = "编写要求提交失败：";
        if (err.response?.data?.msg) errorMsg += err.response.data.msg;
        else if (err.message.includes('Network Error')) errorMsg += '网络错误';
        else if (err.response?.status === 401) errorMsg += '未授权（Token失效）';
        else if (err.response?.status === 500) errorMsg += '后端内部错误';
        else errorMsg += '系统未知错误';
        this.$message.error(errorMsg);
        callback(false);
      }
    },
    async getRequireInfo(projectId) {
      const requestUrl = `${this.baseApi}/system/require/getInfoByProjectId`;
      try {
        const res = await axios({
          url: requestUrl,
          method: 'get',
          headers: { ...this.headers },
          params: { projectId }
        });
        const response = res.data || {};
        const data = response.data || {};
        this.surveyIndustryKeynoteTags = data.surveyIndustryKeynote 
      ? data.surveyIndustryKeynote.split(',').filter(tag => tag.length <= 20) 
      : [];
    this.surveyRequireTags = data.surveyRequire 
      ? data.surveyRequire.split(',').filter(tag => tag.length <= 20) 
      : [];
    this.knowledgeBaseTags = data.knowledgeBaseList
      ? data.knowledgeBaseList.map(item => ({
        fileName: item.originFileName.length > 30 ? item.originFileName.slice(0, 30) + '...' : item.originFileName,
        fileUrl: item.fileUrl,
        delFlag: item.delFlag || '0'
      }))
      : [];
    this.fileList = this.formatFileList(this.knowledgeBaseTags);
    
    this.syncToParent(); 
    
  } catch (err) {
        let errMsg = '查询编写要求失败：';
        if (err.response?.data?.msg) errMsg += err.response.data.msg;
        else if (err.message.includes('Network Error')) errMsg += '网络错误';
        else if (err.response?.status === 401) errMsg += '未授权（Token失效）';
        else if (err.response?.status === 500) errMsg += '后端内部错误';
        else errMsg += '系统未知错误';
        this.$message.error(errMsg);
      }
    }
  }
};
</script>

<style scoped>
::v-deep .knowledge-upload .el-upload-list {
  display: none !important;
}

.project-form {
  width: 700px;
  margin: 0 auto;
  background-color: #fff;
  padding: 20px 0;
}

.form-container {
  width: 100%;
}

.form-row {
  margin-bottom: 25px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.form-item.full-width {
  width: 100%;
}

.label-wrap {
  font-size: 14px;
  color: #333;
}

.tag-container {
  width: 99%;
  min-height: 130px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px 15px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.tags-wrap {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: flex-start;
  flex: 1;
  overflow-y: auto;
  padding-bottom: 5px;
}

.tag-item {
  height: 32px;
  line-height: 32px;
  padding: 0 12px;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}

.tag-item.file-tag {
  background-color: #e8f4f8;
  border-color: #409eff;
}

.input-upload-group {
  display: flex;
  align-items: center;
  width: 100%;
  flex-shrink: 0;
}

.input-add-group {
  display: flex;
  gap: 8px;
  align-items: center;
  flex: 1;
}

.knowledge-input-group {
  max-width: calc(100% - 90px);
}

.custom-input {
  flex: 1;
  height: 32px;
  background-color: #f5f7fa !important;
  border-radius: 4px;
}

.add-btn {
  width: 80px;
  height: 32px;
  padding: 0;
}

.upload-btn {
  width: 80px;
  height: 32px;
  padding: 0;
}

.knowledge-upload {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  margin-left: 12px;
}

::v-deep .el-input__inner {
  border: none !important;
  box-shadow: none !important;
  height: 32px;
  line-height: 32px;
}

::v-deep .tags-wrap::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::v-deep .tags-wrap::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background-color: #ccc;
}

::v-deep .knowledge-upload .el-upload--button {
  display: flex;
  align-items: center;
}

::v-deep .el-input__count {
  font-size: 12px;
  color: #999;
}
</style>